package com.wechat.service.account.starter.customMenu;

import com.alibaba.fastjson.JSONObject;
import com.wechat.service.account.dto.customMenu.ConditionalMenuCreateReqDTO;
import com.wechat.service.account.dto.customMenu.MenuCreateReqDTO;
import com.wechat.service.account.starter.BaseWechatService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

/**
 * @Author yanggld
 * @Date 2019/7/12-17:13
 * @Description
 * 个性化菜单接口
 */
@Slf4j
@Service
public class ConditionalMenuService extends BaseWechatService {

	/**
	 * 创建个性化菜单
	 * @param dto
	 * @return
	 */
	public boolean createConditionalMenu(ConditionalMenuCreateReqDTO dto){
		log.info("********创建个性化菜单参数:{}********",JSONObject.toJSONString(dto));
		ResponseEntity<JSONObject> responseEntity = restTemplate.postForEntity(buildcreateConditionalMenuUrl(), dto, JSONObject.class);
		JSONObject body = responseEntity.getBody();
		log.info("********创建个性化菜单结果:{}********",body);
		if (body.containsKey("menuid")) {
			return true;
		}
		return false;
	}

	/**
	 * 删除个性化菜单
	 * @param menuId
	 * @return
	 */
	public boolean deleteConditionalMenu(String menuId){
		JSONObject params = new JSONObject();
		params.put("menuid",menuId);
		log.info("********删除个性化菜单参数:{}********",JSONObject.toJSONString(params));
		ResponseEntity<JSONObject> responseEntity = restTemplate.postForEntity(buildDelConditionalMenuUrl(), params, JSONObject.class);
		JSONObject body = responseEntity.getBody();
		log.info("********删除个性化菜单结果:{}********",body);
		if (0 == body.getInteger("errcode")) {
			return true;
		}
		return false;
	}

	/**
	 * 测试个性化菜单匹配结果
	 * @param userId 可以是粉丝的OpenID，也可以是粉丝的微信号。
	 * @return
	 */
	public Object matchMenu(String userId){
		JSONObject params = new JSONObject();
		params.put("user_id",userId);
		log.info("********个性化菜单匹配参数:{}********",JSONObject.toJSONString(params));
		ResponseEntity<JSONObject> responseEntity = restTemplate.postForEntity(buildMatchMenuUrl(), params, JSONObject.class);
		JSONObject body = responseEntity.getBody();
		log.info("********个性化菜单匹配结果:{}********",body);
		return body;
	}


	public String buildcreateConditionalMenuUrl(){
		return "https://api.weixin.qq.com/cgi-bin/menu/addconditional?access_token="+accessTokenService.getAccessToken();
	}

	public String buildDelConditionalMenuUrl(){
		return "https://api.weixin.qq.com/cgi-bin/menu/delconditional?access_token="+accessTokenService.getAccessToken();
	}

	public String buildMatchMenuUrl(){
		return "https://api.weixin.qq.com/cgi-bin/menu/trymatch?access_token="+accessTokenService.getAccessToken();
	}
}
